<template>
	<view class="timetable">
		<!-- <view class="header">
      <view class="header-item" v-for="(item,index) in week" :key="item" :style="{ color: xingqiColor == true && currentXingqi === item? '#87cefa' : '#000000' }">
		{{ item }}
	</view>
    </view> -->
		<view class="header">
			<view class="month">{{month}}</view>
			<!-- <view class="header-item" v-for="(item,index) in weekAddDate" :key="item" :style="{ color: xingqiColor == true && ('周' + currentXingqi) === item.xingqi? '#0000FF' : '#000000' }"> -->
			<view class="header-item" v-for="(item,index) in weekAddDate" :key="item" :style="{ color: '#000000' }">
				<view class="item"
					:style="{'color': ((item.xingqi =='周'+currentXingqi) && xingqiColor ) ? '#23b8ff' : ''}">
					<text class="itemDate">{{ item.date }}</text>
					<text class="itemXingqi">{{ item.xingqi }}</text>
				</view>
			</view>
		</view>

		<view class="main">
			<view class="row" v-for="(item,index) in timetableType" :key="index">
				<view class="time-item">
					<view class="index">{{ item.index }}</view>
					<view class="time">{{ item.name }}</view>
				</view>
			</view>

			<view class="course-container">
				<view class="week" v-for="(week, weekIndex) in courseData" :key="weekIndex">
					<view class="courseList" v-for="(course,newIndex) in week" :key="newIndex">
						<view @tap="handleCourseClick(course, weekIndex, newIndex)" class="course"
							:style="{ height: (course.length * 68) + 'px', background: course.backgroundColor }"
							v-if="course.length > 0">
							<view>
								{{ course.name }}
							</view>
							<view>
								{{course.classRoom}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-popup v-model="show" mode="center" border-radius="14" width="600rpx" height="420rpx" style="position: absolute;">
					<view class="pop">
						<u-form :model="form" ref="uForm">
							<!-- <view class="tableHeader">{{selcetCourse.name}}</view> -->
							<!-- <u-divider color="#fa3534" half-width="200" border-color="#6d6d6d">  </u-divider> -->
							<!-- <u-form-item label="教师" img="../../../static/icon/教师管理.png">
							<view class="text">{{selcetCourse.teacher}}</view>
						</u-form-item>
						<u-form-item label="教室" img="../../../static/icon/教室.png">
							<view class="text">{{selcetCourse.classRoom | filterFun}}</view>
						</u-form-item>
						<u-form-item label="周次">
							<view class="text">{{selcetCourse.weekStr}}</view>
						</u-form-item>
						<u-form-item label="节次">
							<view class="text">{{selcetCourse.sectionStr}}</view>
						</u-form-item> -->
							<view class="ui-all">
								<view class="courseNameBox">
									<view class="courseName">{{selcetCourse.name}}</view>
								</view>
		
								<view class="ui-list">
									<text>教师</text>
									<input type="text" :value="selcetCourse.teacher" placeholder-class="place"
										disabled="disabled" />
								</view>
								<view class="ui-list">
									<text>教室</text>
									<!-- 不用处理了 -->
									<!-- 							<input type="text" :value="selcetCourse.classRoom | filterFun" placeholder-class="place"
										disabled="disabled" /> -->
									<input type="text" :value="selcetCourse.classRoom" placeholder-class="place"
										disabled="disabled" />
								</view>
		<!-- 						<view class="ui-list">
									<text>周次</text>
									<input type="text" :value="selcetCourse.weekStr" placeholder-class="place"
										disabled="disabled" />
								</view>
								<view class="ui-list">
									<text>节次</text>
									<input type="text" :value="selcetCourse.sectionStr" placeholder-class="place"
										disabled="disabled" />
								</view> -->
								<view class="ui-list">
									<text>时间</text>
									<input type="text" :value="selcetCourse.time" placeholder-class="place"
										disabled="disabled" />
								</view>
								<text class="deleteCourse" @click="deleteCourse" v-if="canDelete">删除</text>
							</view>
						</u-form>
					</view>
				</u-popup>
		
				<view>
					<u-modal v-model="saveCourse" title="添加课程" :show-cancel-button=true @confirm="confirm">
						<view class="ui-all">
							<view class="ui-list">
								<text>课程名</text>
								<input type="text" placeholder="请输入课程名" v-model="addCourseForm.name"
									placeholder-class="place" />
							</view>
							<view class="ui-list">
								<text>教师</text>
								<input type="text" placeholder="请输入教师" v-model="addCourseForm.teacher"
									placeholder-class="place" />
							</view>
							<view class="ui-list">
								<text>教室</text>
								<input type="text" placeholder="请输入教室" v-model="addCourseForm.classRoom"
									placeholder-class="place" />
							</view>
						</view>
					</u-modal>
				</view>

	</view>
</template>

<script>
	export default {

		name: 'Timetable',
		props: {
			currentWeek: '',
			selectWeek: '',
			saveCourse: false,
			xingqiColor: false,
			canDelete: false,
			timetableType: {
				type: Array,
				default: () => {
					return []
				}
			},

			timetables: {
				type: Array,
				default: () => {
					return []
				}
			},
			palette: {
				type: Array,
				default: () => {
					return []
				}
			}
		},
		// computed: {
		// 	borderColor() {

		// 	}
		// },
		// watch: {
		// 	// 使用watch来响应数据的变化
		// 	timetables: {
		// 		handler(newVal, oldVal) {

		// 			this.$nextTick(() => {
		// 				this.timetables = newVal;
		// 			})
		// 			console.log(newVal, 111)
		// 		},
		// 		deep: true,
		// 	}
		// },
		// computed:{
		// 	timetableType(){
		// 	  if(getApp().globalData.isHaiZhu == true){
		// 	  	return [
		// 	  	  { index: '1', name: '08:00' },
		// 	  	  { index: '2', name: '08:50' },
		// 	  	  { index: '3', name: '09:50' },
		// 	  	  { index: '4', name: '10:40' },
		// 	  	  { index: '5', name: '11:30' },
		// 	  	  { index: '6', name: '14:30' },
		// 	  	  { index: '7', name: '15:20' },
		// 	  	  { index: '8', name: '16:20' },
		// 	  	  { index: '9', name: '17:10' },
		// 	  	  { index: '10', name: '19:30' },
		// 	  	  { index: '11', name: '20:20' },
		// 	  	  { index: '12', name: '21:10' }
		// 	  	]
		// 	  }else{
		// 	  	return [
		// 	  	  { index: '1', name: '08:40' },
		// 	  	  { index: '2', name: '09:30' },
		// 	  	  { index: '3', name: '10:30' },
		// 	  	  { index: '4', name: '11:20' },
		// 	  	  { index: '5', name: '     ' },
		// 	  	  { index: '6', name: '13:30' },
		// 	  	  { index: '7', name: '14:20' },
		// 	  	  { index: '8', name: '15:20' },
		// 	  	  { index: '9', name: '16:10' },
		// 	  	  { index: '10', name: '19:00' },
		// 	  	  { index: '11', name: '19:50' },
		// 	  	  { index: '12', name: '20:0' }
		// 	  	]
		// 	  }
		// 	},
		// },
		data() {
			return {
				week: ['一', '二', '三', '四', '五', '六', '日'],
				// allPalette: [...this.palette, '#48a8e4', '#808000', '#32CD32', '	#9932CC'
				// 		, '#228B22','#FFA500', '#4adbc3', '#673ab7', '#FF4500'
				// 		, '#76bfcd', '#b495e1', '#ff9800', '#6495ED','#DAA520'
				// 		,'#FFA500','#D2691E','#FFB6C1','#DDA0DD','#00BFFF','#40E0D0',
				// 		'#FFD700','#FF8C00','#FF7F50','#6A5ACD','#1E90FF','#00CED1',
				// 		'#98FB98','#ADFF2F'],
				allPalette: [...this.palette, '#48a8e4', '#43CD80', '#FFB6C1', '#FFA500', '#4adbc3',
					'#EE7621', '#76bfcd', '#b495e1', '#ff9800', '#6495ED', '#DAA520', '#FFA500',
					'#DDA0DD', '#00BFFF',
					'#FFD700', '#FF8C00', '#FF7F50', '#00CED1',
					'#98FB98', '#ADFF2F','#48a8e4','#43CD80','#FFB6C1','#ADADAD'
				],
				nameArr: [],
				show: false,
				selcetCourse: {},
				selectSection: -1,
				month: ''
			}
		},
		filters: {
			filterFun: function(value) {
				if (value) {
					value = value.substring(1);
					return value;
				}
			}
		},
		computed: {
			currentXingqi() {

				let xingqi = "日一二三四五六".charAt(new Date().getDay());
				console.log('当前星期', xingqi)
				return xingqi
			},
			weekAddDate() {
				var timestamp;
				var isTrue = true;

				function GetDateStr(AddDayCount) {
					var dd;

					// timestamp = (Date.parse(new Date())) / 1000;
					// if ((timestamp != (Date.parse(new Date('2022-02-21'))) / 1000) &&
					// 	isTrue) { //由于现在的日期不对，所以直到02-21号之前都要设置固定的日期
					// 	dd = new Date('2022-02-21');
					// } else {

					// 	isTrue = false; //到21号后，不等于21号但不会执行上面
					// }
					dd = new Date();
					dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期；
					var y = dd.getFullYear();
					var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1); //获取当前月份的日期，不足10补0
					var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); //获取当前几号，不足10补0
					return y + "-" + m + "-" + d;
				}
				let vm = this

				// 2-21号前，这里要先固定为周一
				let xingqi;
				// if ((timestamp != (Date.parse(new Date('2022-02-21'))) / 1000) &&
				// 	isTrue) { //由于现在的日期不对，所以直到02-27号之前都要设置固定的日期
				// 	xingqi = "一"
				// } else {

				// }
				xingqi = "日一二三四五六".charAt(new Date().getDay());


				// let xingqi = "日一二三四五六".charAt(new Date().getDay());


				let today = new Date().getDate()
				let index = -9999
				let weekAddDate = [{
						xingqi: '周一',
						date: ''
					}, {
						xingqi: '周二',
						date: ''
					}, {
						xingqi: '周三',
						date: ''
					},
					{
						xingqi: '周四',
						date: ''
					}, {
						xingqi: '周五',
						date: ''
					}, {
						xingqi: '周六',
						date: ''
					}, {
						xingqi: '周日',
						date: ''
					}
				]
				for (let i = 0; i < 7; i++) {
					if (weekAddDate[i].xingqi == '周' + xingqi) {
						// weekAddDate[i].date = today
						index = i
						break
					}
				}
				for (let j = 0; j < 7; j++) {
					if (j == 0) {
						vm.month = GetDateStr(((vm.selectWeek - vm.currentWeek) * 7 + (j - index))).substring(5, 7) + '月';
						// console.log('vm.selectWeek', vm.selectWeek);
						// console.log('vm.currentWeek', vm.currentWeek)
					}
					weekAddDate[j].date = GetDateStr(((vm.selectWeek - vm.currentWeek) * 7 + (j - index))).substring(8,
						10);
					// console.log(GetDateStr(((vm.selectWeek - vm.currentWeek) * 7 + (j - index))))
					// console.log(weekAddDate[j].date)
				}

				return weekAddDate
			},
			courseData() {
				let vm = this
				vm.xingqi = "日一二三四五六".charAt(new Date().getDay());
				// 为数据标记背景颜色的函数
				let paletteIndex = 0
				const getBackgroundColor = (nameAndClassRoom) => {
					// let index = (vm.nameArr || []).findIndex((item) => item === nameAndClassRoom)
					let index = (vm.nameArr || []).findIndex((item) => item === nameAndClassRoom)

					if (index == -1) {
						// console.log('执行')
						vm.nameArr.push(nameAndClassRoom)
						index = paletteIndex
					}
					const backgroundColor = this.allPalette[index]
					paletteIndex++
					return backgroundColor
				}

				// 合并
				const listMerge = []
				this.timetables.forEach(function(list, i) {
					if (!listMerge[i]) { //给listMerge初始化7个数组内容
						listMerge[i] = []
					}
					let newIndex = 0;
					// console.log(list,'每一天')
					list.forEach(function(item, index) { //每一个item就是一小节课，index为0-11
						// console.log(item, index, '每一节')
						if (!index) { //每天的第一节课会进来，即index = 0
							// console.log(index)
							return listMerge[i].push({
								infoId: item.id,
								name: item.courseName,
								classRoom: item.local,
								teacher: item.teacher,
								// weekStr: item.weekStr,
								time: item.time,
								sectionStr: item.sectionStr,
								length: 1,
								newIndex: newIndex++,
								backgroundColor: item.courseName === '' ? 'none' :
									getBackgroundColor(
										item.courseName + item.local)
							})
						}
						// console.log('不是第一节课');
						// console.log((listMerge[i][index - 1] || {}).name)
						//每天的不是第一节课会进到这里
						if (item.courseName === (listMerge[i][index - 1] || {}).name && item &&
							item.local === (listMerge[i][index - 1] || {}).classRoom) {
							// console.log('执行')
							const sameIndex = (listMerge[i][index - 1] || {}).sameIndex;
							// console.log(sameIndex,'sameIndex')
							if (sameIndex || sameIndex === 0) {
								listMerge[i][sameIndex].length++ //判断一次课有多长
								return listMerge[i].push({
									infoId: item.id,
									name: item.courseName,
									classRoom: item.local,
									teacher: item.teacher,
									// weekStr: item.weekStr,
									// sectionStr: item.sectionStr,
									time: item.time,
									length: 0,
									newIndex: newIndex++,
									sameIndex: sameIndex
								})
							}
							listMerge[i][index - 1].length++
							return listMerge[i].push({
								infoId: item.id,
								name: item.courseName,
								classRoom: item.local,
								teacher: item.teacher,
								time: item.time,
								// weekStr: item.weekStr,
								// sectionStr: item.sectionStr,
								length: 0,
								newIndex: newIndex++,
								sameIndex: index - 1
							})
						} else {
							return listMerge[i].push({
								infoId: item.id,
								name: item.courseName,
								classRoom: item.local,
								teacher: item.teacher,
								// weekStr: item.weekStr,
								// sectionStr: item.sectionStr,
								time: item.time,
								length: 1,
								newIndex: newIndex++,
								backgroundColor: item.courseName === '' ? 'none' :
									getBackgroundColor(
										item.courseName + item.local)
							})
						}
					})
				})
				this.nameArr = [];
				// console.log('数据111',listMerge)
				return listMerge
			},
			todayWeekIndex() {
				let weekIndex = new Date().getDay() - 1
				if (weekIndex === -1) {
					weekIndex = 6
				}
				return weekIndex
			}
		},
		methods: {
			AddDays(num) {
				var newdate = new Date();
				var newtimems = newdate.getTime() - (num * 24 * 60 * 60 * 1000);
				newdate.setTime(newtimems);
				var time = newdate.getFullYear() + "-" + (newdate.getMonth() + 1) + "-" + newdate.getDate();
				return time;
			},
			confirm() {
				let vm = this
			},

			handleCourseClick(course, weekIndex, courseIndex) {
				const data = {
					infoId: course.infoId,
					index: courseIndex + 1,
					classRoom: course.classRoom,
					teacher: course.teacher,
					length: course.length,
					week: this.week[weekIndex],
					weekIndex: weekIndex,
					name: course.name,
					time: course.time,
					dayOfWeek:"",
					section:"",
					local:"",
					// weekStr: course.weekStr,
					// sectionStr: course.sectionStr
				}
				console.log(data)
				this.deleteInfoId = course.infoId
				//    console.log(`星期${data.week}; 第${data.index}节课; 课程名:${data.name};教室:${data.classRoom}; 老师:${data.teacher};
				// 周次:${data.weekStr}; 节次:${data.sectionStr}; 课节:${data.length}`)
				this.selcetCourse = data;
				// console.log(this.selcetCourse)
				if (data.name != "") {
					uni.navigateTo({
						url:`../../page_courseContent/courseContent/courseContent?week=${data.week}&name=${data.name}&classRoom=${data.classRoom}&teacher=${data.teacher}&time=${data.time}&selectWeek=${this.selectWeek}&infoId=${this.selcetCourse.infoId}`
					})
				}
			},
			deleteCourse() {
				let vm = this
				uni.showModal({
					title: '您确定要删除该课吗？',
					confirmText: '确定',
					cancelText: '取消',
					async success(i) {
						if (i.confirm) {
							uni.showLoading({
								title: '删除中'
							});
							let header = new Object()
							header = {
								// 'Content-Type': 'application/json',
								'Authority': uni.getStorageSync("Authority")
							}
							// let body = new Object()
							// let arr = new Array()

							// let weekIndex = parseInt("一二三四五六日".indexOf(vm.selcetCourse.week))
							// let startSection = parseInt(vm.selcetCourse.index)
							// let length = parseInt(vm.selcetCourse.length)
							// for (let i = startSection; i < startSection + length; i++) {
							// 	arr.push(vm.timetables[weekIndex][i - 1].infoId)
							// }
							// let infoIdList = arr.join()
							// body.infoIdList = infoIdList
							let res = await getApp().UniRequest("/coursePlus/authority?id=" + vm.selcetCourse
								.infoId, "DELETE", "",
								header)
							console.log('删除结果', res);
							if (res.code == 20000) {
								uni.hideLoading()
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 2000
								});
								vm.show = false
								uni.showLoading({
									title: '正在加载课表',
									mask: true
								})
								vm.$emit('getCourseNewData', vm.selectWeek)
							} else {
								uni.hideLoading()
								uni.showToast({
									title: '请稍后重试',
									icon: 'error',
									duration: 2000
								});
								vm.show = false
							}
							// uni.request({
							// 	url: 'http://112.74.188.40:9001/coursePlus/authority?id=' + vm
							// 		.selcetCourse.infoId, //仅为示例，并非真实接口地址。
							// 	header: header,
							// 	method: 'DELETE',
							// 	success: (res) => {
							// 		console.log('删除结果', res.data);

							// 	}
							// })

						}
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.timetable {
		background: white;
		border: 1px solid #E4E7ED;
		border-radius: 8rpx;


		.header {
			padding-left: 68rpx; //88
			height: 80rpx;
			display: flex;
			align-items: center;
			background: #F5F7FA;

			.month {
				position: absolute;
				left: 10rpx;
				font-weight: bold;
				color: #23b8ff;
			}

			.header-item {
				flex: 1;
				text-align: center;
				font-weight: bold;
			}
		}

		.main {
			position: relative;

			.row {
				height: 70px;
				position: relative;
				margin-top: -16rpx;

				&:after {
					content: '';
					height: 0;
					width: 100%;
					position: absolute;
					bottom: 0;
					left: 0;
					border-top: 1rpx solid #E4E7ED;
					border-bottom: 1rpx solid #E4E7ED;

				}

				.time-item {
					height: 100%;
					width: 70rpx; //100
					text-align: center;
					background: #F5F7FA;

					.index {
						color: #000000;
						// color: #006400;
						font-weight: bold;
						padding-bottom: 8rpx;
						// padding-top: 0rpx;
						font-size: 25rpx;

					}

					.time {
						font-size: 25rpx;
						margin-top: -13rpx;
					}
				}
			}

			.course-container {
				position: absolute;
				top: 10rpx;
				left: 68rpx; //88
				width: calc(100% - 68rpx);
				height: 100%;
				display: flex;

				.week {
					// border-left: 1rpx solid #E4E7ED;
					flex: 1;
					width: 0;
					flex-grow: 1;
					display: flex;
					flex-direction: column;
					margin-top: 0rpx;

					.courseList {
						word-break: break-all;
						padding: 1px 1px;
						color: white;
						overflow: hidden;
						font-family: Verdana; //monospace

						.course {
							padding: 8rpx;
							border-radius: 6rpx; //16
							font-size: 12px;
							text-align: left;
						}
					}
				}
			}
		}
	}

	.ui-all {
		padding: 20rpx 40rpx;

		// height: 400rpx;
		.avatar {
			width: 100%;
			text-align: left;
			padding: 20rpx 0;
			border-bottom: solid 1px #f2f2f2;
			position: relative;

			.imgAvatar {
				width: 140rpx;
				height: 140rpx;
				border-radius: 50%;
				display: inline-block;
				vertical-align: middle;
				overflow: hidden;

				.iavatar {
					width: 100%;
					height: 100%;
					display: block;
				}
			}

			text {
				display: inline-block;
				vertical-align: middle;
				color: #8e8e93;
				font-size: 28rpx;
				margin-left: 40rpx;
			}

			&:after {
				content: ' ';
				width: 20rpx;
				height: 20rpx;
				border-top: solid 1px #030303;
				border-right: solid 1px #030303;
				transform: rotate(45deg);
				-ms-transform: rotate(45deg);
				/* IE 9 */
				-moz-transform: rotate(45deg);
				/* Firefox */
				-webkit-transform: rotate(45deg);
				/* Safari 和 Chrome */
				-o-transform: rotate(45deg);
				position: absolute;
				top: 85rpx;
				right: 0;
			}
		}

		.ui-list {
			width: 100%;

			text-align: left;
			padding: 20rpx 0;
			border-bottom: solid 1px #f2f2f2;
			position: relative;

			text {
				color: #4a4a4a;
				font-size: 28rpx;
				display: inline-block;
				vertical-align: middle;
				min-width: 150rpx;
			}

			input {
				color: #030303;
				font-size: 30rpx;
				display: inline-block;
				vertical-align: middle;
			}

			button {
				color: #030303;
				font-size: 30rpx;
				display: inline-block;
				vertical-align: middle;
				background: none;
				margin: 0;
				padding: 0;

				&::after {
					display: none;
				}
			}

			picker {
				width: 90%;
				color: #030303;
				font-size: 30rpx;
				display: inline-block;
				vertical-align: middle;
				position: absolute;
				top: 30rpx;
				left: 150rpx;
			}

			textarea {
				color: #030303;
				font-size: 30rpx;
				vertical-align: middle;
				height: 150rpx;
				width: 100%;
				margin-top: 50rpx;
			}

			.place {
				color: #999999;
				font-size: 28rpx;
			}
		}

		.right:after {
			content: ' ';
			width: 20rpx;
			height: 20rpx;
			border-top: solid 1px #030303;
			border-right: solid 1px #030303;
			transform: rotate(45deg);
			-ms-transform: rotate(45deg);
			/* IE 9 */
			-moz-transform: rotate(45deg);
			/* Firefox */
			-webkit-transform: rotate(45deg);
			/* Safari 和 Chrome */
			-o-transform: rotate(45deg);
			position: absolute;
			top: 40rpx;
			right: 0;
		}

		.save {
			background: #030303;
			border: none;
			color: #ffffff;
			margin-top: 40rpx;
			font-size: 28rpx;
		}
	}

	.courseNameBox {
		position: relative;
		// margin: auto;
		border-bottom: solid 1px #f2f2f2;
		text-align: center;

		.courseName {
			position: relative;
			color: #000000;
			font-size: 30rpx;
			font-weight: bold;
		}
	}

	.deleteCourse {
		position: absolute;
		margin-top: 20rpx;
		right: 275rpx;
		color: red;
		font-weight: bold;
		letter-spacing: 4px
	}

	.item {
		display: flex;
		flex-direction: column;

		.itemDate {}

		.itemXingqi {}
	}
</style>
